<template>
  <div class="attach">
    <div v-show="canEdit || currentAudit" class="header" style="align-items: center;">
      <p style="margin-right: 30px"><strong>项目编号：</strong>{{ projectBuild.projectNo }}</p>
      <p style="margin-right: 30px"><strong>项目名称：</strong>{{ projectBuild.projectName }}</p>
      <!-- <p ><a-button type="primary" @click="reload(null)">刷新</a-button></p> -->
    </div>
    <div class="content">
      <div class="projectFile">
        <div class="title" v-show="mainAttaches.length>0">
          项目文件
          <div class="download-control">
            <!-- <a-button type="primary"  @click="reload('main')">刷新</a-button> -->
            <a-button type="primary"  v-bind:disabled="!downloadAndViewProject" @click="downLoadBatch(0)">下载</a-button>
            <a-button style="width:auto" type="primary"  v-bind:disabled="!downloadAndViewProject" @click="downLoadBatch(1)">一键打包下载</a-button>
            <a-button class="default" @click="coreDeleteBatch" v-bind:disabled="!canEdit && !currentAudit"
              >删除</a-button
            >
          </div>
        </div>
        <ul v-if="mainAttaches.length>0">
          <div v-for="(attach, index) in mainAttaches">
            <main-attach 
            :ref="attach.code"
            :key="index"
            :attach="attach"
            :project-build-id="projectBuildId"
            :can-edit="canEdit || currentAudit" 
            :change-id="changeId"
            :mineUploads="['项目概算表']"
            :item-status="itemStatus"
            @mainAttachSelected="mainAttachSelected"
            @showAttach="showAttachFromChild"
            @httpRequest="httpRequest"
            @minUpload="engineeBudget=true"
            >
            </main-attach>
          </div>
        </ul>

       
        <!-- 大文件上传工程图纸附件 -->
        <div v-if="!!drawingAttache">
              <div class="title" ><span v-if="drawingAttache.required" style="color: red">&nbsp;*</span>{{drawingAttache.name}}</div>
              <hte-upload :ref="drawingAttache.code" dbKey="Trd"
              :busField="changeId ? 'ProjectBuildChange' : 'ProjectBuild'"
              :busKey="changeId ? projectBuildId+'_'+changeId : projectBuildId"
              :uploadDisabled="!(normalCanEdit || currentAudit)"
              :deleteDisabled="!(normalCanEdit || currentAudit)"
              :previewDisabled="!downloadAndViewProject"
              :downloadDisabled="!downloadAndViewProject"
              :refreshDisable="true"
              :busType="drawingAttache.code"
              :onSuccess="(response,file,fileList)=>fileUploadSuccess(response,file,fileList,drawingAttache.code)"
              :onRemove="(idsArr,selectionRows)=>deleteDrawing(idsArr,selectionRows,drawingAttache.code)"
              :ftpKey="drawingAttache.ftpKey"
              :zipFileName="projectBuild.projectNo+projectBuild.projectName+'图纸'"></hte-upload>
               <!-- :onPreview="(record)=>showAttach(record.id,record.uploader,record.fileName,true, 'main',drawingAttache.ftpKey)" -->
          </div>
         
        <div class="title"  v-if="otherAttaches.length > 0">其他附件</div>
        <div class="infoTips"  v-if="otherAttaches.length > 0">
          <a-icon type="exclamation-circle" theme="filled" style="color: #47a4fa" />
          请按项目附件表提醒的文件清单上传文件，还有其他附件的可以上传到此处。
        </div>
        <div class="otherAttach" v-if="otherAttaches.length > 0">
          <div class="upload-control" style="display: flex">
            <ht-upload 
              :ref="otherAttaches[0].code"
              class="upload-demo"
              multiple
              dbKey="Trd"
              :busField="changeId ? 'ProjectBuildChange' : 'ProjectBuild'"
              :busKey="changeId ? projectBuildId+'_'+changeId : projectBuildId"
              :disabled="!otherCanEdit"
              :busType="otherAttaches[0].code"
              ftpKey="ftp"
              v-model="otherAttachList"
              :httpRequest="(option)=>httpRequest(option,this.$refs[otherAttaches[0].code],otherAttaches[0].code)"
             
            >
              <el-button size="small" type="primary" style="height: 30px;width:85px;" v-bind:disabled="!otherCanEdit">
                <span style="font-size: 14px;"
                  >上传<span v-if="otherAttaches[0].required" style="color: red">&nbsp;*</span></span
                ></el-button
              >
            </ht-upload>
            <!-- <a-button type="primary" @click="reload('other',{busField:changeId ? 'ProjectBuildChange' : 'ProjectBuild',busKey:changeId ? projectBuildId+'_'+changeId : projectBuildId},this,'otherAttachList')" style="margin-left: 10px">刷新</a-button> -->
            <a-button type="primary" v-bind:disabled="!downloadAndViewOther" @click="otherDownLoadBatch(0)" style="margin-left: 10px">下载</a-button>
            <a-button style="width:auto" type="primary" v-bind:disabled="!downloadAndViewOther" @click="otherDownLoadBatch(1)">一键打包下载</a-button>
            <a-button
              class="default"
              @click="othersDeleteBatch"
              v-bind:disabled="!otherCanEdit"
              >删除</a-button
            >
          </div>
          <a-table
            :row-selection="{ selectedRowKeys: otherAttachSelectedIds, onChange: otherAttachSelected,getCheckboxProps:record=>({props: {
            disabled: !(!record.status || record.status == 'success') , // Column configuration not to be checked
            name: record.status,
          },}) }"
            :columns="otherAttachColumns"
            :data-source="otherAttachDataList"
            bordered
            :pagination="false"
          >
            <template slot="name" slot-scope="text, record">
              <a @click="showAttach(record.key, record.uploader, record.name, true, 'other')">{{ record.name }}</a>
            </template>
          </a-table>
        </div>

        <a-modal 
        title="工程项目预算表"
        :width="1800"
        :visible="engineeBudget"
        @cancel="engineeBudgetClose"
        @ok="engineeBudgetOk">
          <EngineeBudget :projectBuildId="projectBuildId" :projectNo="projectBuild.projectNo" :projectName="projectBuild.projectName" ref="engineeBudgetRef"/>
        </a-modal>

      </div>
    </div>
    
  </div>
</template>
<script>
import $ from 'jquery'
import '@/utils/upload.install.js'
import '@/config/hteupload.install.js';
import { getAction, postAction, getActionAsync ,uploadAttach,getAttaches,previewAttach} from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { formatFileSize, endWith, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
const otherAttachColumns = [
  {
    title: '附件名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '附件大小',
    dataIndex: 'size',
    width: '15%',
  },
  {
    title: '上传时间',
    dataIndex: 'time',
    width: '20%',
  },
  {
    title: '上传者',
    dataIndex: 'uploaderName',
    width: '20%',
  },
]
const FTP_KEY = 'ftp';
export default {
  components: {
    MainAttach: () => import('@/components/tools/projectBuildStup/MainAttach'),
    EngineeBudget: () => import('@/components/tools/project/EngineeBudget')
  },
  data() {
    return {
      projectBuildId: '',
      projectBuild: {},
      mainAttaches: [],
      mainAttacheSelected: [],
      //其他附件字典配置
      otherAttaches: [],
      
      //图纸附件
      drawingAttache:null,
      //图纸功能上线日期
      drawingSplitDate:'2021-12-21',
      //是否显示新的图纸功能
      showDrawingNew:false,
      oldDrawingCodes:['G101','G201','G301','G401','G501','G603','G703'],
      otherAttachList: [],
      otherAttachDataList: [],
      otherAttachColumns,
      otherAttachSelectedIds: [], // Check here to configure the default column
      loading: false,
      attach: {
        getProjectBuildVOWithProjectManagers: '/projectBuild/getProjectBuildVOWithProjectManagers',
        getProjectBuildAttachCodeInfos: '/projectBuild/getProjectBuildAttachCodeInfos',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/common/deleteBatch',
        getAttachInfo: '/tp/attach/getAttaches',
        logAttachAdd: '/projectChange/logAttachAdd',
         logAttachDelete: '/projectChange/logAttachDelete'
      },
      url: {
        getRequiredAttachCode: '/projectBuild/getRequiredAttachCode',
        codeInfo:'/manage/codeInfo/list'
      },
      canEdit: false,
      otherCanEdit: false, //其他附件可编辑
      normalCanEdit:false,//通用附件可编辑
      currentAudit: false,
      downloadAndViewProject: false,
      downloadAndViewOther: false,
      changeId: this.$route.query.changeId,
      canDoSave: this.$route.query.canDoSave=='true' ? true : false,
      engineeBudget: false,
      itemStatus:0
    }
  },
  mounted() {
    this.projectBuildId = this.$route.query.projectBuildId
    var currentAudit = this.$route.query.currentAudit
    this.currentAudit = currentAudit == 'true' ? true : false
    this.initData()
  },
  computed: {},
  watch: {
    otherAttachList:{ deep: true,
      handler(fileList)  { 
      this.otherAttachDataListFresh()
    }},
  },
  methods: {

    engineeBudgetOk(){
      this.engineeBudgetData = this.$refs.engineeBudgetRef.getCurrentTableList()
      console.log('this.projectBuildId:',this.projectBuildId)
      if(this.engineeBudgetData && this.engineeBudgetData.length > 0){
        this.engineeBudgetData.forEach(item =>{
          if(item.strId && !item.strId.startsWith('add')){
            item.id = item.strId
          }else{
            item.projectBuildId = this.projectBuildId;
          }
        })
        console.log('engineeBudgetData:',JSON.stringify(this.engineeBudgetData))
        postAction(this.url.saveEngineeBudget,this.engineeBudgetData).then((res)=>{
          if(res.code == 200){
            console.log('保存成功')
          }
        })
      }
      this.engineeBudget=false;
      window.location.reload()
      
    },

    engineeBudgetClose(){
      this.engineeBudget=false;
      window.location.reload();
    },
    httpRequest(options,$ref,attachCode){
       let vm = this
    
       uploadAttach(options).then(result => {
         
         result.data.forEach(item=>{
           item.status='success'
            item.percentage = 100
         })
          
          $ref.fileListDefault.push.apply($ref.fileListDefault, result.data)
          options.onSuccess(result.data)
         
          //项目变更，记录附件变更日志
          if(!!this.changeId){
               let attachFile =  result.data
              attachFile.forEach(item=>{
                  var res= item;
                  this.logAttachAdd(res,attachCode)
                })
            }
         
         
        }).catch(err => {
          options.onError(err)
        })
    },
    logAttachAdd(file,attachCode){
        var res= file;
      if(!!this.changeId){
              
              
                var data={
                  busKey:this.projectBuildId,
                  fileName:res.fileName, 
                  changeTarget: 7,
                  attachCode:attachCode  
                }
                getAction(this.attach.logAttachAdd, data)
                .then((res) => {
                  if (res.code == 200) {
                    console.log('附件记录日志成功:'+res.fileName)
                  } else {
                    this.$message.warning('附件记录附件变更日志失败:' + res.msg)
                  }
                })
                .catch((res) => {
                  this.$message.warning('附件记录附件变更日志异常:' + res.msg)
                })
            }
    },
    logAttachDelete(res,attachCode){
      
      if(!!this.changeId){
              
              
                var data={
                  busKey:this.projectBuildId,
                  fileName:res.fileName, 
                  changeTarget: 7,
                  attachCode:attachCode  
                }
                getAction(this.attach.logAttachDelete, data)
                .then((res) => {
                  if (res.code != 200) {
                     this.$message.warning('附件记录附件变更日志失败:' + res.msg)
                  } 
                })
                .catch((res) => {
                  this.$message.warning('附件记录附件变更日志异常:' + res.msg)
                })
            }
    },
    fileUploadSuccess(response,file,fileList,attachCode){
       //项目变更，记录附件变更日志
      
          this.logAttachAdd(file,attachCode)
        
      },
    showAttachFromChild(record) {
      this.showAttach(record.id, record.uploader, record.fileName, false, 'main')
    },

    showAttach(id, uploader, fileName, autoDownload,type,ftpKey = 'ftp') {
      if (!this.checkPermisson(uploader,type)) {
        if(type=='main' && this.changeId){
          this.$message.warning('仅有项目经理可以查看变更中的项目附件')
        }else{
          this.$message.warning('仅有该附件上传人、审批人、抄送人、项目经理、副经理可以查看!')
        }
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        if (autoDownload) {
          this.doDownLoadBatch(id)
          return
        }
        this.$message.warning('该附件类型不支持预览，请下载附件查看')
        return
      }
      let params={
        id:id,
        ftpKey:ftpKey
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
            if (this.projectBuild.projectClass == '40' || this.projectBuild.projectClass == '61') {
              window.open(process.env.BASE_URL+'/pdf/web/normalViewer.html?file=' + url)
            } else {
              window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
            }
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    checkPermisson(uploader,type) {
      debugger
      var currUser = Vue.ls.get(USER_INFO).username
      if (type=='other' && (uploader == currUser || this.downloadAndViewOther)) {
        return true
      }
      if(type=='main' && this.downloadAndViewProject){
        return true
      }
      return false
    },
    otherAttachDataListFresh() {
      let vm = this
      this.otherAttachDataList = []
      let index = 0
      this.otherAttachList.forEach((item) => {
        var size = formatFileSize(item.size)
        this.otherAttachDataList.push({
          key: item.id || item.uid,
          name: item.fileName||item.name,
          size: size,
          time: item.uploadTime,
          uploader: item.uploader,
          uploaderName: item.uploaderName,
          status:item.status || 'success',
          percentage:item.percentage,
          uid:item.uid
        })
      })
    },
    getMainAttachSelected() {
      var attachIdArr = []
      this.mainAttacheSelected.forEach((item) => {
        if (item.attachIds != null && item.attachIds.length > 0) {
          attachIdArr = attachIdArr.concat(item.attachIds)
        }
      })
      return attachIdArr.join(',')
    },
     getMainAttachCode() {
      var attachCode = []
      this.mainAttacheSelected.forEach((item) => {
        if (item.attachIds != null && item.attachIds.length > 0) {
          item.attachIds.forEach((code)=>{
            attachCode.push(item.code)
          })
        }
      })
      return attachCode.join(',')
    },
    mainAttachSelected(attachCode, checkedValues) {
      var needPush = true
      this.mainAttacheSelected.forEach((item) => {
        if (item.code === attachCode) {
          item.attachIds = checkedValues
          needPush = false
        }
      })
      if (needPush) {
        this.mainAttacheSelected.push({ code: attachCode, attachIds: checkedValues })
      }
      console.log(this.mainAttacheSelected)
    },
    start() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.otherAttachSelectedIds = []
      }, 1000)
    },
    otherAttachSelected(selectedRowKeys) {
      this.otherAttachSelectedIds = selectedRowKeys
    },
    downLoadBatch(status = 0){
      let vm = this
      if(status==1){
      let attachIds = []   
      this.mainAttaches.forEach((item) => {
        if (item.code) {
            if(vm.$refs[item.code]){
              let ids = []
              if(vm.$refs[item.code] instanceof Array){
                 ids = vm.$refs[item.code][0].getAttachIds()
              }else{
               ids = vm.$refs[item.code].getAttachIds()
              }
              attachIds.push(...ids)
            }
          }
        })

        this.doDownLoadBatch(attachIds)
      return
      }
      var attachIds = this.getMainAttachSelected()
      if(attachIds==null || attachIds.length<1){
        this.$message.warning('请选择需要下载的项目文件');
        return;
      }
      this.doDownLoadBatch(attachIds)
    },
    downLoadBatchAll(){

    },
    doDownLoadBatch(attachIds,ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      var href =
        this.API_BASE_URL +
        this.attach.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey='+ftpKey+'&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    coreDeleteBatch() {
      var attachIds = this.getMainAttachSelected()
      let attachCodes = this.getMainAttachCode()
      
      
      if(attachIds!=null && attachIds.length>0){
        this.delFiles(attachIds,attachCodes,this.mainDeleteFileList)
       
      }else{
        this.$message.warning('请选择要删除的项目文件')
      }
    },
    mainDeleteFileList(){
      let vm = this
      this.mainAttacheSelected.forEach((item) => {
        
        if (item.code) {
          if(vm.$refs[item.code]){
          if(vm.$refs[item.code] instanceof Array){
              vm.$refs[item.code][0].deleteFileList()
          }else{
            vm.$refs[item.code].deleteFileList()
          }
          }
        }
      })

    },
    otherDownLoadBatch(status){
      if(status==1){
        let ids = []
        
         this.otherAttachList.map(item=>{
            ids.push(item.id)
          })
        this.doDownLoadBatch(ids)
        return
      }
      if (this.otherAttachSelectedIds != null && this.otherAttachSelectedIds.length > 0) {
        this.doDownLoadBatch(this.otherAttachSelectedIds)
      } else {
        this.$message.warning('请选择要下载的其它附件')
      }
    },
    othersDeleteBatch() {
      if (this.otherAttachSelectedIds != null && this.otherAttachSelectedIds.length > 0) {
        let attachCodes = []
        this.otherAttachSelectedIds.forEach(item=>{
          attachCodes.push(this.otherAttaches[0].code)
        })
        this.delFiles(this.otherAttachSelectedIds.join(','),attachCodes.join(","),this.othersDeleteFileList)
        
      } else {
        this.$message.warning('请选择要删除的其它附件')
      }
    },
    othersDeleteFileList(){
      let vm = this
      
      this.otherAttachSelectedIds.forEach(item=>{
        let index = -1
        if(!item.status||item.status=='success'){
           index = this.otherAttachList.findIndex(attach=>{return attach.id==item})
        }
        if(item.status=='fail'){
           index = this.otherAttachList.findIndex(attach=>{return attach.uid==item})
        }
        if(index != -1){
            this.otherAttachList.splice(index,1);
        } 
      })
      this.otherAttachSelectedIds = []
    },
    deleteDrawing(attachIds,rows,attachCode){
      let attachCodes = []
        rows.forEach(element => {

          this.logAttachDelete(element,attachCode)
          
        });

    },
    delFiles(attachIds,attachCodes,callBack, ftpKey = 'ftp') {
      
      const that = this
        Modal.confirm({
        title: '确认删除',
        content: '此操作将删除选中附件, 是否继续?',
        onOk: function () {
          getAction(that.attach.deleteBatch, { attachIds: attachIds,attachCodes:attachCodes, dbKey: 'Trd', ftpKey: ftpKey, changeId: that.changeId})
          .then((res) => {
            if (res.code == 1) {
              that.$message.success('批量删除成功')
              
              callBack()
              //this.reload()
              // setTimeout(function () {
              //   window.location.reload()
              // }, 500)
            } else {
              that.$message.warning('批量删除失败:' + res.msg)
            }
          })
          .catch((res) => {
            that.$message.warning('批量删除失败:' + res.msg)
          })
        }})
      
      
      
     
      
    },
    getAttaches(dataDefault,vm,key){
        key = !!key?key:'filelist'
       if (((dataDefault.busKey && dataDefault.busField))) {
         vm[key] = []
        getAttaches(dataDefault).then(result => {
          
          if(result.code == 1){
          vm[key] = result.data

          }else{
            console.log(`查询附件列表失败：${result.msg}`)
          }
        }).catch(err => {
          console.log(`查询附件列表失败：${err.message}`)
        })
       }
      },
    reload(type,dataDefault,vmUpload,key){
      //刷新     
      var vm = this
      

      if(type == 'main' ){
          this.mainAttaches = []
          this.mainAttacheSelected = []
      }else if (type=='other' ){
          
         let dataDefault = {
            dbKey: 'Trd',
            ftpKey:'ftp',
            busKey: this.changeId ? this.projectBuildId+'_'+this.changeId : this.projectBuildId,
            busField:this.changeId ? 'ProjectBuildChange' : 'ProjectBuild',
            busType:this.otherAttaches[0].code
          }
          this.getAttaches(dataDefault,vm,key)
          this.otherAttachSelectedIds = []
      }else if ( type=='normal' ){
         this.getAttaches(dataDefault,vmUpload,key)
      }else if(!type){
        //刷新全部
        this.mainAttaches = []
        this.mainAttacheSelected = []
        if(this.otherAttaches.length>0 && this.$refs.otherAttachs){
          this.$refs.otherAttachs.fileListDefault=[]
          this.otherAttachList=[]
        }
        this.otherAttaches = []
        this.otherAttachSelectedIds = []
        this.drawingAttache = null
      }
      this.$nextTick(()=>{
        vm.initData()
      })
    },
    initData() {
      var vm = this
      
      getAction(this.attach.getProjectBuildVOWithProjectManagers, { id: this.projectBuildId })
        .then((res) => {
          if (res.code == 200) {
            debugger
            var result = res.result
            //console.log('result:',JSON.stringify(result))
            if (result != null) {
              vm.projectBuild = result
              vm.showDrawingNew=((vm.projectBuild.status===1||new Date(vm.projectBuild.submitDate).getTime()>=new Date(vm.drawingSplitDate).getTime()));
              if (result.projectType != null && result.projectType.length > 0) {
                vm.getRequiredAttachCode()
                debugger
                var currUser = Vue.ls.get(USER_INFO).username
                //状态
                vm.itemStatus = vm.projectBuild.status
                console.log('vm itemstatus: ',vm.itemStatus)
                if (
                  vm.projectBuild.createUserId === currUser ||
                  vm.projectBuild.currentAuditUserId === currUser ||
                  (vm.projectBuild.copyForUserIds != null && vm.projectBuild.copyForUserIds.indexOf(currUser) > -1) ||
                  (vm.projectBuild.projectManagers != null && vm.projectBuild.projectManagers.indexOf(currUser) > -1) ||
                  (vm.projectBuild.assistantProjectManagers != null && vm.projectBuild.assistantProjectManagers.indexOf(currUser) > -1 || 
                  (vm.projectBuild.allAuditors != null && vm.projectBuild.allAuditors.indexOf(currUser) > -1) )
                ) {
                  vm.otherCanEdit = true
                  if (vm.projectBuild.status == 1 && !vm.changeId) { //变更中项目文件不可修改
                    vm.canEdit = true
                  }
                  if(vm.projectBuild.status == 1 || !!vm.changeId){
                    ///创建变更中图纸附件可修改
                    vm.normalCanEdit = true
                  }
                }
                
                if(vm.otherCanEdit || vm.projectBuild.downAndView ){
                  vm.downloadAndViewOther = true;
                  if(vm.changeId){
                    if((vm.projectBuild.projectManagers != null && vm.projectBuild.projectManagers.indexOf(currUser) > -1) || vm.projectBuild.projectSubTypeAdmin){
                      vm.downloadAndViewProject  = true
                    }
                  }else{
                    vm.downloadAndViewProject  = true
                  }
                }
                if(vm.projectBuild.currentAuditUserId === currUser 
                || (vm.projectBuild.copyForUserIds != null && vm.projectBuild.copyForUserIds.indexOf(currUser) > -1) ){
                  vm.currentAudit = true
                }

                // MG类型 分类管理员可以下载附件 code by dr 20220211
                if (vm.projectBuild.projectTypeSubCategory == 'MG' && vm.projectBuild.projectSubTypeAdmin) {
                  vm.downloadAndViewProject  = true
                }
              }
            }
          } else {
            this.$message.warning('查询附件相关信息失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件相关信息异常:' + res.message)
        })
    },
    getRequiredAttachCode() {
      getAction(this.url.codeInfo, {type:this.projectBuild.projectType +'类必传附件'})
        .then((res) => {
          if (res.code == 200) {
            
            this.requiredAttachCode = res.result.records || []
            this.initAttaches(this.projectBuild.projectType)
          } else {
            this.$message.warning('查询必填附件失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询必填附件失败:' + res.message)
        })
    },
    async initAttaches(projectType) {
      var vm = this
      getAction(this.attach.getProjectBuildAttachCodeInfos, { projectType: projectType, timeNodeCode: '1' })
        .then(async (res) => {
          if (res.code == 200) {
            //debugger;
            var result = res.result
            if (result != null) {
              let otherAttaches = []
                let mainAttaches = []
                let drawingAttache = null
              for (let index = 0; index < result.length; index++) {
                const item = result[index];
                
                if (vm.requiredAttachCode != null) {
                  vm.requiredAttachCode.forEach((reqAtt) => {
                    if (reqAtt.code == item.code) {
                      item.required = true
                    }
                  })
                }
                if (item.code == 'other') {
                  otherAttaches.push(item)
                }else if( item.code == 'drawing'  ){
                  if(!vm.showDrawingNew){
                    continue;
                  }
                   item.ftpKey = new String(FTP_KEY) 
                  //工程项目图纸附件ftp
                  if(vm.projectBuild.projectClass == '40'){
                       item.ftpKey = 'ftpDRA'
                  }
                 
                  let ftpRes = await getActionAsync(this.url.codeInfo,{type:projectType+'类立项附件FTP',parentid: '1',code:item.code})
                  
                  if(ftpRes.success){
                        if(ftpRes.result.records.length>0){
                          item.ftpKey = ftpRes.result.records[0].name
                        }
                  }
                  drawingAttache = item
                  
                } 
                else {
                  if(vm.oldDrawingCodes.indexOf(item.code)>=0){
                    if(!vm.showDrawingNew){
                      mainAttaches.push(item);
                    }
                  }else{
                    mainAttaches.push(item);
                  }
                }
                
              }
              vm.otherAttaches = otherAttaches
                vm.mainAttaches = mainAttaches
                vm.drawingAttache = drawingAttache
            }
          } else {
            this.$message.warning('查询附件字典配置失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件字典配置失败:' + res.message)
        })
    }


  },
}
</script>
<style lang="less" scoped>
/deep/.el-upload-list {
  display: none;
}
/deep/.anticon {
  font-size: 16px;
  vertical-align: middle;
}
.otherAttach /deep/ .ant-btn-primary ,.download-control /deep/ .ant-btn-primary{
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #1890FF;
  margin-right: 10px;
}
.otherAttach /deep/ .default,.download-control /deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
/deep/ .ant-table-thead > tr > th {
  background: #dadee9 !important;
}
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/ .ant-table table {
  border-radius: unset;
  line-height: 1;
}
/deep/ .ant-table-tbody .ant-table-row td {
  &:nth-child(2) {
    color: #3e8ee2;
  }
}
/deep/ .ant-table-tbody .ant-table-row td {
  padding-top: 8px;
  padding-bottom: 8px;
}
.attach {
  border: 1px solid #e6e6e6;
  background-color: #fff;
  padding-bottom: 30px;
  .header {
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    padding: 20px 0 0 20px;
  }
  .content {
    padding: 15px;
    .projectFile {
      .title {
        border-left: 3px solid #47a4fa;
        padding: 0 10px;
        .download-control {
          display: inline-block;
          margin-left: 10px;
        }
      }
    }
    ul {
      list-style: none;
      padding: 15px 0;
      border-bottom: 1px solid #f7f7f7;
      li {
        padding: 15px !important;
        border: 1px solid #e8e8e8;
        border-radius: 6px;
        margin-bottom: 15px;
        display: flex;
        align-items: flex-start;
      }
      .upload-demo {
        display: flex;
        /deep/ .el-upload {
          margin-right: 10px;
        }
      }
    }
    .infoTips {
      background: #e6f7ff;
      border: 1px solid #aee1ff;
      border-radius: 4px;
      margin: 20px 0;
      padding: 5px 10px;
      font-size: 12px;
      width: fit-content;
    }
    .otherAttach {
      .upload-control {
        margin-bottom: 15px;
      }
    }
    .btn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}
</style>